package cn.lovemmd.model.mapper;

import cn.lovemmd.model.entity.ModelLog;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

/**
 * 模型日志Mapper接口
 * 
 * @author TLS
 * @since 2024-01-01
 */
@Mapper
public interface ModelLogMapper extends BaseMapper<ModelLog> {
    
    @Select("SELECT COUNT(*) FROM model_log WHERE deleted = 0 AND m_action = 'view'")
    Long countTotalViews();
    
    @Select("SELECT COUNT(*) FROM model_log WHERE deleted = 0 AND m_action = 'view' AND m_time >= DATE_SUB(NOW(), INTERVAL 1 DAY)")
    Long countViewsLast24h();
    
    @Select("SELECT COUNT(*) FROM model_log WHERE deleted = 0 AND m_action = 'view' AND m_time >= DATE_SUB(NOW(), INTERVAL 7 DAY)")
    Long countViewsLast7d();
    
    @Select("SELECT COUNT(*) FROM model_log WHERE deleted = 0 AND m_action = 'view' AND m_time >= DATE_SUB(NOW(), INTERVAL 30 DAY)")
    Long countViewsLast30d();
    
    @Select("SELECT COUNT(*) FROM model_log WHERE deleted = 0 AND m_action = 'view' AND m_id = #{modelId}")
    Long countViewsByModelId(@Param("modelId") Long modelId);
    
    @Select("SELECT COUNT(*) FROM model_log WHERE deleted = 0 AND m_action = 'view' AND m_id = #{modelId} AND m_time >= DATE_SUB(NOW(), INTERVAL 1 DAY)")
    Long countViewsByModelIdLast24h(@Param("modelId") Long modelId);
    
    @Select("SELECT COUNT(*) FROM model_log WHERE deleted = 0 AND m_action = 'view' AND m_id = #{modelId} AND m_time >= DATE_SUB(NOW(), INTERVAL 7 DAY)")
    Long countViewsByModelIdLast7d(@Param("modelId") Long modelId);
    
    @Select("SELECT COUNT(*) FROM model_log WHERE deleted = 0 AND m_action = 'view' AND m_id = #{modelId} AND m_time >= DATE_SUB(NOW(), INTERVAL 30 DAY)")
    Long countViewsByModelIdLast30d(@Param("modelId") Long modelId);
    
    @Select("SELECT ml.m_name, COUNT(mlog.id) as view_count FROM model_log mlog " +
            "LEFT JOIN model_list ml ON mlog.m_id = ml.m_id " +
            "WHERE mlog.deleted = 0 AND ml.deleted = 0 AND mlog.m_action = 'view' " +
            "GROUP BY mlog.m_id, ml.m_name " +
            "ORDER BY view_count DESC LIMIT #{limit}")
    List<Map<String, Object>> selectTopViewedModels(@Param("limit") int limit);
    
    @Select("SELECT DATE(m_time) as date, COUNT(*) as count FROM model_log " +
            "WHERE deleted = 0 AND m_action = 'view' AND m_time >= DATE_SUB(NOW(), INTERVAL 30 DAY) " +
            "GROUP BY DATE(m_time) ORDER BY date")
    List<Map<String, Object>> selectViewTrend();
}
